package com.sky.task;

import com.sky.entity.Student;
import com.sky.mapper.StudentMapper;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class WebSocketTask {
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private StudentMapper studentMapper;
    private static int currentIndex = 0;
//    @Scheduled(cron = "0/5 * * * * ?")
//    public void sendMessageToClient() {
//        log.info("开始发送消息到客户端");
//        webSocketServer.sendToAllClient("这是来自服务端的消息：" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
//    }

    // 这个任务只会执行一次
   // @Scheduled(fixedDelay = Long.MAX_VALUE, initialDelay = 10000)
    public void  sendStudentData() {
        log.info("开始发送学生信息到客户端");
      //  webSocketServer.sendToAllClient2(studentMapper.selectAll());
        List<Student> studentList = studentMapper.selectAll();
        webSocketServer.sendToAllClient2(studentList);
    }
    // 基于websocket实现动态刷新图表
    @Scheduled(fixedDelay = 30000, initialDelay = 5000) // 每 2 秒发送一次
    public void sendStudentData2() {
        log.info("开始发送学生信息到客户端");
        List<Student> studentList = studentMapper.selectAll();
        if (studentList.isEmpty()) return;
        int totalSize = studentList.size();
        int batchSize = 10;
        // 计算本次发送范围
        int endIndex = Math.min(currentIndex + batchSize, totalSize);
        List<Student> subList = studentList.subList(currentIndex, endIndex);
        webSocketServer.sendToAllClient2(subList);
        // 更新索引
        currentIndex = endIndex % totalSize; // 循环播放
    }

}
